package cn.edu.service;

import cn.edu.mapper.BrandMapper;
import cn.edu.mapper.UserMapper;
import cn.edu.pojo.User;
import cn.edu.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author Davey chan
 */
public class UserService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public User login(String username,String password){
        //     获取SqlSession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//      获取Usermapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        调用方法
        User user = mapper.select(username, password);
//释放资源
        sqlSession.close();
        return user;
    }
    public User selectByUsername(String username){
        //     获取SqlSession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//      获取Usermapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //        调用方法
        User user = mapper.selectByusername(username);
        sqlSession.close();
        return user;
    }
    public void addUser(User user){
        //     获取SqlSession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//      获取Usermapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //        调用方法
        mapper.add(user);
        sqlSession.commit();
        sqlSession.close();
    }
    public boolean register(User user){
        //获取SqlSession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取Usermapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 判断用户名是否存在
        User u = mapper.selectByusername(user.getUsername());
        if(u==null){
        // 用户不存在
            mapper.add(user);
            sqlSession.commit();
        }
        sqlSession.close();
        return u==null;
    }

}
